<template>
  <view class="pay">
    <!-- 添加地址开始 -->
    <view class="address">
      <view class="addres_info">
        <!-- 展示地址 -->
        <view class="info-title">收货地址：</view>
        <view class="info-addres">{{ address }}</view>
      </view>
    </view>
    <!-- 添加地址结束 -->
    <!-- 购物车开始 -->
    <view class="cart_list_container">
      <!-- 标题 -->
      <view class="cart_title">购物车</view>
      <!-- 商品块 -->
      <view class="cart_list_item" v-for="(item, index) in cart" :key="item.goods_id">
        <navigator open-type="navigate" :url="'../goods_detail/goods_detail?goods_id=' + item.goods_id">
          <!-- 图片 -->
          <image :src="item.goods_small_logo" mode="widthFix"></image>
        </navigator>
        <view class="good_info_row">
          <view class="good_name">
            <!-- 商品名字 -->
            {{ item.goods_name }}
          </view>
          <view class="good_price_num">
            <view class="good_price">¥{{ item.goods_price }}</view>
            <view class="good_edit_row">
              <text>×</text>
              <text>{{ item.num }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 购物车结束 -->
    <!-- 底部工具栏开始 -->
    <view class="btm_tools">
      <!-- 总价 -->
      <view class="tatal_price_row">
        <view class="total_price_warper">
          <text>合计：</text>
          <text class="total_price">¥{{ totalPrice }}</text>
          <view class="total_price_extra">包含运费</view>
        </view>
      </view>
      <!-- 结算 -->
      <view class="order_pay" @tap="pay">支付({{ totalNum }})</view>
    </view>
    <!-- 底部工具栏结束 -->
  </view>
</template>

<script>
import regeneratorRuntime from '../../lib/runtime/runtime.js';
import { request } from '../../request/request.js';
import { uniGetProvider, uniRequestPayment, uniShowToast } from '../../utils/utils.js';
export default {
  onShow() {
    this.showCart();
  },
  data() {
    return {
      address: '',
      cart: [],
      totalNum: 0,
      totalPrice: 0
    };
  },
  methods: {
    /* 刷新购物车页面 */
    showCart() {
      var _me = this;
      // 取缓存购物车
      _me.address = uni.getStorageSync('address');
      _me.cart = uni.getStorageSync('cart') || [];
      _me.cart = _me.cart.filter(function(item) {
        return item.checked == true;
      });
      // 设置变量，全选，总数，总价
      var allChecked = _me.cart.length == 0 ? false : true;
      var totalNum = 0;
      var totalPrice = 0;
      // 遍历计算：全选，总数，总价
      _me.cart.forEach(function(item, index) {
        if (item.checked == true) {
          totalNum = totalNum + 1;
          totalPrice = totalPrice + item.goods_price * item.num;
        } else {
          allChecked = false;
        }
      });
      // console.log(_me.cart);
      _me.allChecked = allChecked;
      _me.totalNum = totalNum;
      _me.totalPrice = totalPrice;
    },
    /* 去支付 */
    async pay() {
      var _me = this;
      // 判断是否有 token
      var token = uni.getStorageSync('token');
      if (token == '') {
        // 没有token
        uni.navigateTo({
          url: '../auth/auth'
        });
      } else {
        // 有token
        // 【1.创建订单】
        try {
          var goods = [];
          _me.cart.forEach(function(item) {
            goods.push({
              goods_id: item.goods_id,
              goods_number: item.num,
              goods_price: item.goods_price
            });
          });
          let res = await request({
            url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/create',
            method: 'POST',
            header: {
              Authorization: token
            },
            data: {
              order_price: _me.totalPrice,
              consignee_addr: _me.address,
              goods: goods
            }
          });
          // console.log('[创建订单]成功', res);
          // 获取订单号
          var order_number = res.data.message.order_number;
          console.log('订单号', order_number);

          // 【2.获取支付参数】
          let res2 = await request({
            url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/req_unifiedorder',
            method: 'POST',
            header: {
              Authorization: token
            },
            data: {
              order_number: order_number
            }
          });
          // console.log('[获取支付参数]成功', res2);
          // 获取 pay 对象
          var payObj = res2.data.message.pay;
          console.log('pay对象', payObj);
          // 【3.发起支付】
          // 3.1 获取支付服务商
          let res3 = await uniGetProvider({ service: 'payment' });
          // console.log(res3);
          // 支付服务商(默认第一个)
          var payment = res3.provider[0];
          // console.log('payment: ' + payment);
          // 3.1 支付
          // 支付代码块
          {
            console.log('支付代码块');
            // var res4;
            // switch (payment) {
            //   case 'wxpay':
            //     res4 = await uniRequestPayment({
            //       provider: payment,
            //       timeStamp: payObj.timeStamp,
            //       nonceStr: payObj.nonceStr,
            //       package: payObj.package,
            //       signType: payObj.signType,
            //       paySign: payObj.paySign
            //     });
            //     break;
            //   default:
            //     res4 = await uniShowToast({
            //       title: '其他平台暂不支持支付',
            //       mask: true,
            //       duration: 1000,
            //       icon: 'none'
            //     });
            //     break;
            // }
          }

          // 【4.查看订单状态】
          let res5 = await request({
            url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/chkOrder',
            method: 'POST',
            header: {
              Authorization: token
            },
            data: {
              order_number: order_number
            }
          });
          console.log(res5);

          // 把支付过的商品从购物车移除
          let newCart = uni.getStorageSync('cart');
          newCart = newCart.filter(function(item){
             return item.checked == false
          });
          uni.setStorageSync('cart', newCart);
          // 跳转到订单页面
          // 先跳转到购物车，再跳转到订单页面
          // 这样可以防止返回上一页回到支付页面
          uni.switchTab({
            url:"../cart/cart",
            complete() {
              uni.navigateTo({
                url: '/pages/order/order'
              });
            }
          })
        } catch (error) {
          //TODO handle the exception
          console.log('[创建订单]失败', error);
          switch (error.errMsg) {
            case 'requestPayment:fail no permission':
              await uniShowToast({
                title: '无创建支付权限',
                mask: true,
                duration: 1000,
                icon: 'none'
              });
              break;
            default:
              break;
          }
        }
      }
    }
  }
};
</script>

<style lang="scss">
.pay {
  padding-bottom: 90rpx;
  /* 添加地址开始 */
  .address {
    height: 136rpx;
    .addres_info {
      padding: 10rpx 20rpx;
      .info-title {
        height: 36rpx;
        font-size: 36rpx;
      }
      .info-addres {
        height: 70rpx;
        margin-top: 10rpx;
        font-size: 36rpx;
        line-height: 36rpx;
        text-indent: 1em;
      }
    }
  }
  /* 添加地址结束 */
  /* 购物车开始 */
  .cart_list_container {
    .cart_title {
      color: $themeColor;
      padding: 20rpx;
      border: {
        top: 2rpx solid #cccccc;
        bottom: 2rpx solid #cccccc;
      }
    }
    .cart_list_item {
      display: flex;
      padding: 20rpx 0rpx;
      border: {
        top: 2rpx solid #cccccc;
        bottom: 2rpx solid #cccccc;
      }
      navigator {
        flex: 2;
        display: flex;
        justify-content: center;
        align-items: center;
        // background-color: #00ff00;
        image {
          width: 80%;
        }
      }
      .good_info_row {
        flex: 6;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        // background-color: #0000ff;
        .good_name {
          /* 超出隐藏 */
          display: -webkit-box;
          overflow: hidden;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
        }
        .good_price_num {
          display: flex;
          justify-content: space-between;
          .good_price {
            color: $themeColor;
            font-size: 30rpx;
            font-weight: bolder;
          }
          .good_edit_row {
            display: flex;
            padding-right: 20rpx;
            text {
              width: 50rpx;
              height: 50rpx;
              padding: 0rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 36rpx;
            }
          }
        }
      }
    }
  }
  /* 购物车结束 */
  /* 底部工具栏开始 */
  .btm_tools {
    display: flex;
    z-index: 100;
    position: fixed;
    left: 0;
    bottom: var(--window-bottom);
    width: 100%;
    height: 90rpx;
    background-color: #ffffff;
    border-top: 2rpx solid #cccccc;
    .tatal_price_row {
      flex: 7;
      display: flex;
      flex-direction: column;
      .total_price_warper {
        text-align: right;
        .total_price {
          color: $themeColor;
          font-size: 30rpx;
          font-weight: bolder;
        }
      }
      .total_price_extra {
        font-size: 30rpx;
      }
    }
    .order_pay {
      flex: 3;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 34rpx;
      font-weight: bolder;
      color: #ffffff;
      background-color: $themeColor;
    }
  }
  /* 底部工具栏结束 */
}
</style>
